<template>
  <div ref="documentDivRef" class="document-page">
    <div class="attachment-left">
      <preview-pdf ref="pdfRef" :url="selectDocument?.url" height="100%" width="100%" />
    </div>
    <div class="video-right">
      <page-right-list :text-content="spans">
        <template #list>
          <div class="select-list">
            <div class="select-header">
              <div class="header-text">
                <span class="header-text-w">文档</span>
                <span class="open-video-num">{{ documentNum }}/{{ document.length }}</span>
              </div>
              <div class="header-down">
                <a-button type="link" @click="downloadAll">全部下载</a-button>
              </div>
            </div>
            <div class="line-svg"></div>
            <div class="list-content-box my-scrollbar">
              <div
                v-for="(item, index) in document"
                :key="index"
                style="width: 100%"
                class="list-content"
                :class="[item.status ? 'active' : '']"
                @click="handleBtn(item.id, index)"
              >
                <i class="iconfont icon-file-line" style="color: #649af0"></i>
                <span class="list-content-left elliptical-1" :title="item.fileName">{{ item.fileName }}</span>
                <span class="list-download-show iconfont icon-download-2-line" @click="downloadOne(item)"></span>
              </div>
            </div>
          </div>
        </template>
      </page-right-list>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { nextTick, ref, watch } from 'vue'

  import manualMessage from '@/components/ManualMessage/index'
  import PreviewPdf from '@/components/PreviewPdf/index.vue'
  import { fetchDownload, minioApi } from '@/services/api'

  import PageRightList from './PageRightList.vue'

  export interface DataSetCardProps {
    spans?: any
    document?: any
  }
  const selectDocument = ref<any>({
    url: ''
  })

  const documentDivRef = ref()
  const pdfRef = ref()

  let reload = true

  const handleIntersection = (enteries: IntersectionObserverEntry[]) => {
    if (!reload) return
    for (let item of enteries) {
      if (item.intersectionRatio > 0) {
        pdfRef.value.refresh()
        reload = false
        return
      }
    }
  }

  const observer = new IntersectionObserver(handleIntersection)
  let props = withDefaults(defineProps<DataSetCardProps>(), {
    spans: {},
    document: () => []
  })
  let watchData = watch(
    () => props.document,
    () => {
      if (props.document.length > 0) {
        nextTick(() => {
          watchData()
          // 将第一个定为选择状态
          selectDocument.value = props.document[0]
          //eslint-disable-next-line
          props.document[0]['status'] = true
          observer.observe(documentDivRef.value)
        })
      }
    }
  )

  const documentNum = ref<number>(1)

  const handleBtn = (id: string, num: number) => {
    documentNum.value = num + 1
    props.document.map((item: any) => {
      if (id !== item.id) {
        item['status'] = false
      } else {
        item['status'] = true
        selectDocument.value = item
      }
    })
  }

  // 单个下载
  const downloadOne = async (obj: any) => {
    try {
      let res = await minioApi.download({ fileName: obj.fileUrl })
      manualMessage.loading('数据准备中,请耐心等待...', 0)
      await fetchDownload(res.data, `${obj.fileName}`)
      manualMessage.destroy()
      message.success({ content: '文件下载成功', icon: '', key: 'downloading', duration: 2 })
    } catch (error: any) {
      manualMessage.destroy()
      message.error('文件下载失败')
    } finally {
    }
  }
  // 全部下载
  const downloadAll = async () => {
    manualMessage.loading('数据准备中,请耐心等待...', 0)

    const downloadPromiseList = props.document.map(
      async (obj: any) =>
        new Promise(rs => {
          minioApi.download({ fileName: obj.fileUrl }).then(({ data }: any) => {
            fetchDownload(data, `${obj.fileName}`).then(rs)
          })
        })
    )

    Promise.all(downloadPromiseList)
      .finally(() => {
        manualMessage.destroy()
      })
      .then(() => {
        message.success({ content: '文件下载成功', icon: '', key: 'downloading', duration: 2 })
      })
      .catch(() => {
        message.error('下载失败')
      })
  }
</script>
<style lang="less" scoped>
  .document-page {
    display: flex;
    width: 100%;
    gap: 24px;

    .attachment-left {
      overflow: hidden;
      width: 1026px;
      border: 1px solid @border1;
      border-radius: 10px;
      flex-shrink: 0;
    }

    .video-right {
      overflow: hidden;
      width: 328px;
    }
  }

  .select-list {
    display: flex;
    align-items: flex-start;
    padding: 20px 12px;
    margin-top: 16px;
    width: 328px;
    height: 395px;
    max-height: 395px;
    background: #ebf0f7;
    border: 1px solid @border1;
    border-radius: 10px;
    flex-direction: column;
    gap: 12px;
    flex: 1 0 0;

    .select-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 8px;
      width: 100%;

      .header-text {
        display: flex;
        gap: 12.5px;
        align-items: center;

        .header-text-w {
          color: @text02;
          .font14b();
        }

        .open-video-num {
          color: @text03;
          .font14();
        }
      }
    }

    .line-svg {
      margin-bottom: 12px;
      width: 100%;
      height: 0;
      border-top: 1px solid @border1;
    }

    .list-content {
      display: flex;
      gap: 8px;
      align-items: center;
      padding: 0 8px;
      width: 100%;
      height: 36px;
      min-height: 36px;
      border-radius: 6px;
      cursor: pointer;

      &:hover {
        background: rgba(0, 0, 0, 0.05);
      }

      &.active {
        background: #fff;
        font-weight: 700;
      }

      & + .list-content {
        margin-top: 2px;
      }

      .list-content-left {
        width: calc(100% - 24px);
        color: @text01;
        .font14();
      }

      .list-content-right {
        color: @text03;
        .font14();
      }

      .list-download-show {
        color: #009cf8;
      }
    }

    .list-content-box {
      display: flex;
      overflow-y: auto;
      width: 100%;
      flex-direction: column;
      height: 280px;
    }
  }
</style>
